import api from '@/api';

const state = {
  // 商品列表
  goodsList: [],
  
  // 商品分类
  categories: [],
  
  // 当前分类
  currentCategory: null,
  
  // 搜索关键词
  searchKeyword: '',
  
  // 排序方式
  sortBy: 'default', // default, price_asc, price_desc, sales, commission
  
  // 分页信息
  pagination: {
    page: 1,
    pageSize: 20,
    total: 0,
    hasMore: true
  },
  
  // 我的商品
  myGoods: [],
  
  // 商品详情
  goodsDetail: null,
  
  // 商品加载状态
  loading: false,
  
  // 收藏商品
  favoriteGoods: []
};

const mutations = {
  // 设置商品列表
  SET_GOODS_LIST(state, goods) {
    state.goodsList = goods;
  },
  
  // 添加商品到列表
  APPEND_GOODS_LIST(state, goods) {
    state.goodsList = [...state.goodsList, ...goods];
  },
  
  // 设置分类
  SET_CATEGORIES(state, categories) {
    state.categories = categories;
  },
  
  // 设置当前分类
  SET_CURRENT_CATEGORY(state, category) {
    state.currentCategory = category;
  },
  
  // 设置搜索关键词
  SET_SEARCH_KEYWORD(state, keyword) {
    state.searchKeyword = keyword;
  },
  
  // 设置排序方式
  SET_SORT_BY(state, sortBy) {
    state.sortBy = sortBy;
  },
  
  // 设置分页
  SET_PAGINATION(state, pagination) {
    state.pagination = { ...state.pagination, ...pagination };
  },
  
  // 重置分页
  RESET_PAGINATION(state) {
    state.pagination = {
      page: 1,
      pageSize: 20,
      total: 0,
      hasMore: true
    };
  },
  
  // 设置我的商品
  SET_MY_GOODS(state, goods) {
    state.myGoods = goods;
  },
  
  // 添加我的商品
  ADD_MY_GOOD(state, goods) {
    state.myGoods.unshift(goods);
  },
  
  // 更新我的商品
  UPDATE_MY_GOOD(state, goods) {
    const index = state.myGoods.findIndex(item => item.id === goods.id);
    if (index > -1) {
      state.myGoods.splice(index, 1, goods);
    }
  },
  
  // 删除我的商品
  DELETE_MY_GOOD(state, goodsId) {
    const index = state.myGoods.findIndex(item => item.id === goodsId);
    if (index > -1) {
      state.myGoods.splice(index, 1);
    }
  },
  
  // 设置商品详情
  SET_GOODS_DETAIL(state, detail) {
    state.goodsDetail = detail;
  },
  
  // 设置加载状态
  SET_LOADING(state, loading) {
    state.loading = loading;
  },
  
  // 设置收藏商品
  SET_FAVORITE_GOODS(state, goods) {
    state.favoriteGoods = goods;
  },
  
  // 添加收藏
  ADD_FAVORITE_GOOD(state, goods) {
    const exists = state.favoriteGoods.findIndex(item => item.id === goods.id);
    if (exists === -1) {
      state.favoriteGoods.unshift(goods);
    }
  },
  
  // 移除收藏
  REMOVE_FAVORITE_GOOD(state, goodsId) {
    const index = state.favoriteGoods.findIndex(item => item.id === goodsId);
    if (index > -1) {
      state.favoriteGoods.splice(index, 1);
    }
  },
  
  // 清除商品状态
  CLEAR_GOODS_STATE(state) {
    state.goodsList = [];
    state.currentCategory = null;
    state.searchKeyword = '';
    state.sortBy = 'default';
    state.pagination = {
      page: 1,
      pageSize: 20,
      total: 0,
      hasMore: true
    };
    state.myGoods = [];
    state.goodsDetail = null;
    state.loading = false;
    state.favoriteGoods = [];
  }
};

const actions = {
  // 获取商品列表
  async getGoodsList({ commit, state }, params = {}) {
    try {
      commit('SET_LOADING', true);
      
      const requestParams = {
        page: state.pagination.page,
        pageSize: state.pagination.pageSize,
        category_id: state.currentCategory?.id,
        keyword: state.searchKeyword,
        sort_by: state.sortBy,
        ...params
      };
      
      const response = await api.goods.getList(requestParams);
      const { list, pagination } = response.data;
      
      if (params.append) {
        commit('APPEND_GOODS_LIST', list);
      } else {
        commit('SET_GOODS_LIST', list);
      }
      
      commit('SET_PAGINATION', pagination);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取商品列表失败:', error);
      return { success: false, error: error.message };
    } finally {
      commit('SET_LOADING', false);
    }
  },
  
  // 获取商品分类
  async getCategories({ commit }) {
    try {
      const response = await api.goods.getCategories();
      commit('SET_CATEGORIES', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取商品分类失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 设置分类筛选
  setCategory({ commit, dispatch }, category) {
    commit('SET_CURRENT_CATEGORY', category);
    commit('RESET_PAGINATION');
    return dispatch('getGoodsList');
  },
  
  // 搜索商品
  searchGoods({ commit, dispatch }, keyword) {
    commit('SET_SEARCH_KEYWORD', keyword);
    commit('RESET_PAGINATION');
    return dispatch('getGoodsList');
  },
  
  // 设置排序
  setSortBy({ commit, dispatch }, sortBy) {
    commit('SET_SORT_BY', sortBy);
    commit('RESET_PAGINATION');
    return dispatch('getGoodsList');
  },
  
  // 加载更多
  loadMore({ commit, state, dispatch }) {
    if (!state.pagination.hasMore || state.loading) {
      return Promise.resolve();
    }
    
    commit('SET_PAGINATION', { page: state.pagination.page + 1 });
    return dispatch('getGoodsList', { append: true });
  },
  
  // 获取商品详情
  async getGoodsDetail({ commit }, goodsId) {
    try {
      commit('SET_LOADING', true);
      const response = await api.goods.getDetail(goodsId);
      commit('SET_GOODS_DETAIL', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取商品详情失败:', error);
      return { success: false, error: error.message };
    } finally {
      commit('SET_LOADING', false);
    }
  },
  
  // 获取我的商品
  async getMyGoods({ commit }) {
    try {
      const response = await api.goods.getMyGoods();
      commit('SET_MY_GOODS', response.data.list);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取我的商品失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 发布商品
  async publishGoods({ commit }, goodsData) {
    try {
      const response = await api.goods.publish(goodsData);
      commit('ADD_MY_GOOD', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('发布商品失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 更新商品
  async updateGoods({ commit }, { id, goodsData }) {
    try {
      const response = await api.goods.update(id, goodsData);
      commit('UPDATE_MY_GOOD', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('更新商品失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 删除商品
  async deleteGoods({ commit }, goodsId) {
    try {
      const response = await api.goods.delete(goodsId);
      commit('DELETE_MY_GOOD', goodsId);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('删除商品失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 上下架商品
  async toggleGoodsStatus({ commit }, { id, status }) {
    try {
      const response = await api.goods.toggleStatus(id, { status });
      
      // 更新我的商品状态
      const goods = { id, status };
      commit('UPDATE_MY_GOOD', goods);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('更新商品状态失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 获取收藏商品
  async getFavoriteGoods({ commit }) {
    try {
      const response = await api.goods.getFavorites();
      commit('SET_FAVORITE_GOODS', response.data.list);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取收藏商品失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 收藏商品
  async favoriteGoods({ commit }, goodsId) {
    try {
      const response = await api.goods.favorite(goodsId);
      commit('ADD_FAVORITE_GOOD', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('收藏商品失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 取消收藏
  async unfavoriteGoods({ commit }, goodsId) {
    try {
      const response = await api.goods.unfavorite(goodsId);
      commit('REMOVE_FAVORITE_GOOD', goodsId);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('取消收藏失败:', error);
      return { success: false, error: error.message };
    }
  }
};

const getters = {
  // 商品列表
  goodsList: state => state.goodsList,
  
  // 分类列表
  categories: state => state.categories,
  
  // 当前分类
  currentCategory: state => state.currentCategory,
  
  // 搜索关键词
  searchKeyword: state => state.searchKeyword,
  
  // 排序方式
  sortBy: state => state.sortBy,
  
  // 分页信息
  pagination: state => state.pagination,
  
  // 我的商品
  myGoods: state => state.myGoods,
  
  // 商品详情
  goodsDetail: state => state.goodsDetail,
  
  // 加载状态
  loading: state => state.loading,
  
  // 收藏商品
  favoriteGoods: state => state.favoriteGoods,
  
  // 是否有更多数据
  hasMore: state => state.pagination.hasMore,
  
  // 总数
  total: state => state.pagination.total,
  
  // 当前页
  currentPage: state => state.pagination.page
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};